const express = require('express')
      router = express.Router()

//渲染首页
 router.get('/',(req,res) =>{
 	
  Question.find().exec(function(err,data){
   	  	data.forEach(function(ele,num){
   	  		var id = ele.id
   	  		Answer.find({questionId:id}).sort({createTime:-1}).populate('ownerId').exec(function(err,item){
   	  			Question.update({_id:id},{ans:item}).exec(function(err,data){
   	  			})
   	  		})
   	  	})
   	  })
   	  
   	  
   	  var page = req.query.page || 1
					page = parseInt(page)
					var countOfPage = 2
			setTimeout(function(){		
				Question.count().exec(function(err,total){
					var count = Math.ceil(total / countOfPage) //向上取整
					var pages = []
					for(var i=0;i<count;i++){
						pages[i] = i+1
					}
					
						Question
   	  	.find()
   	  	.sort({createTime:-1})
   	  	.skip((page-1)*2)
   	  	.limit(countOfPage)
   	  	.populate('ownerId')
   	  	.exec(function(err,data){
   	  		res.render('index',{
   	  			question:data,
   	  			title:'首页',
					 	page,
					 	count,
					 	pages
   	  		})
   	  	})
				})
		  },50)
})


///////注册页面渲染//////
  router.get('/regist',(req,res) =>{
  	res.render('user/register',{
  		title:"注册",
  		back:true
  	})
  })

/////提问页面渲染/////
router.get('/ask',(req,res) =>{
	res.render('ask',{
		title:'提问'
	})
})

/////回答页面渲染////////
router.get('/answer',(req,res) =>{
	res.render('answer',{
		title:'回答'
	})
})

////头像部分的渲染////
router.get('/photo',(req,res) =>{
	res.render('user/photo',{
		title:'个人信息'
	})
})



//////登录页面渲染////////////////

router.get('/signin',(req,res) =>{
	res.render('user/login',{
		title:'登录',
		back:true
	})
})

//删除
router.get('/same',(req,res)=>{
	var id = req.cookies.questionId
	var name= req.cookies.username
	Question.find({_id:id},function(err,data){
       if(data[0].ownerId.username==name){
			send(res,'success','文件删除成功')
	   }else{
		   send(res,'fail','你没有权限删除')
	   }
	}).populate('ownerId')
})


router.get('/remove',(req,res)=>{
	var id = req.cookies.questionId
	var name= req.cookies.username
	Question.find({_id:id},function(err,data){
		Question.remove({_id:id},function(err,data){
		})
		Answer.remove({questionId:id},function(err,data){
		})
	send(res,'success','文件删除成功')
	}).populate('ownerId')

})




module.exports = router